import logging


# === 方案三：对比方式检测logger名称 ===

def get_current_logger_names():
    """获取当前所有logger名称"""
    return set(logging.Logger.manager.loggerDict.keys())


def detect_new_loggers(import_and_use_func):
    """
    检测新导入库产生的logger名称

    Args:
        import_and_use_func: 导入并使用第三方库的函数
    """
    # 获取导入前的logger列表
    before_loggers = get_current_logger_names()

    # 执行导入和使用操作
    import_and_use_func()

    # 获取导入后的logger列表
    after_loggers = get_current_logger_names()

    # 找出新增的logger
    new_loggers = after_loggers - before_loggers

    return sorted(list(new_loggers))


# 使用示例
if __name__ == "__main__":
    # 定义导入和使用第三方库的函数
    def use_paddleocr():
        try:
            from paddleocr import PaddleOCR
            # 初始化以触发logger创建
            ocr = PaddleOCR(device='cpu', lang='ch')
        except Exception as e:
            print(f"导入或使用库时出错: {e}")


    def use_requests():
        try:
            import requests
            # 发起请求以触发日志
            requests.get('https://www.baidu.com', timeout=5)
        except Exception as e:
            print(f"导入或使用库时出错: {e}")


    # 检测PaddleOCR的logger
    print("检测PaddleOCR的logger名称:")
    paddleocr_loggers = detect_new_loggers(use_paddleocr)
    for logger_name in paddleocr_loggers:
        print(f"  {logger_name}")

    print("\n检测requests的logger名称:")
    requests_loggers = detect_new_loggers(use_requests)
    for logger_name in requests_loggers:
        print(f"  {logger_name}")
